package com.hsmw.api.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hsmw.api.config.jwt.CurrentHsmwUserUtils;
import com.hsmw.api.config.jwt.LoginUser;
import com.hsmw.api.controller.pub.TencentPushUtils;
import com.hsmw.api.mapper.*;
import com.hsmw.api.utils.GaoDeInfoUtils;
import com.hsmw.api.utils.YLWUtils;
import com.hsmw.api.vo.*;
import com.hsmw.common.base.BasePage;
import com.hsmw.common.base.BaseService;
import com.htn.common.core.base.DataResponse;
import com.htn.common.core.constant.*;
import com.htn.common.core.utils.StringUtils;
import com.hsmw.domain.*;
import com.hsmw.domain.vo.*;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.*;

@Slf4j
@Service
@Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class HsmwConcretePlantInfoService extends BaseService<HsmwConcretePlantInfoMapper, HsmwConcretePlantInfo> {

    @Autowired
    private HsmwOrderMapper hsmwOrderMapper;

    @Autowired
    private HsmwConcretePlantInfoMapper hsmwConcretePlantInfoMapper;

    @Autowired
    private HsmwConcreteInfoMapper hsmwConcreteInfoMapper;

    @Autowired
    private HsmwConcreteOperateService hsmwConcreteOperateService;

    @Autowired
    private CurrentHsmwUserUtils currentHsmwUserUtils;

    @Autowired
    private HsmwConcreteOperateMapper hsmwConcreteOperateMapper;

    @Autowired
    private HsmwOrderVehicleRequestService hsmwOrderVehicleRequestService;

    @Autowired
    private HsmwConcreteOperateRecordMapper hsmwConcreteOperateRecordMapper;

    @Autowired
    private HsmwConstructionPositionService hsmwConstructionPositionService;

    @Autowired
    private HsmwOrderVehicleRelationService hsmwOrderVehicleRelationService;

    @Autowired
    private HsmwUserDriverService hsmwUserDriverService;

    @Autowired
    private HsmwItemMapper hsmwItemMapper;

    @Autowired
    private HsmwConcreteOperateRecordService hsmwConcreteOperateRecordService;

    @Autowired
    private HsmwOrderService hsmwOrderService;







    @Autowired
    private HsmwItemConcreteRelationService hsmwItemConcreteRelationService;


    @Autowired
    private HsmwDriverNewsService hsmwDriverNewsService;


    @Autowired
    private HsmwHtnUserService hsmwHtnUserService;
    /**
     * 查询混凝土订单
     * @return
     */
    public DataResponse findConcreteOrderList(String param) {

        LoginUser hsmwUser = currentHsmwUserUtils.getCurrentUserInfo();
        if(hsmwUser == null){
            return new DataResponse(CommonConstants.ResponseStatus.UNAUTHORIZED,"登陆人查询信息为空");
        }
        HsmwConcretePlantInfo hsmwConcretePlantInfo = hsmwConcretePlantInfoMapper.selectOne(new LambdaQueryWrapper<HsmwConcretePlantInfo>().eq(HsmwConcretePlantInfo::getUserId, hsmwUser.getId()));
        // 未完成订单
        if(hsmwConcretePlantInfo == null){
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"没有搅拌站信息");
        }
        List<OrderAndItemVO> hsmwOrders = hsmwOrderMapper.findConcreteOrderList(param,hsmwConcretePlantInfo.getId());
        if(CollectionUtil.isNotEmpty(hsmwOrders)){
            for (OrderAndItemVO hsmwOrder : hsmwOrders) {
                String itemId = hsmwOrder.getItemId();
                HsmwItem hsmwItem = hsmwItemMapper.selectById(itemId);
                if(hsmwItem != null){
                    hsmwOrder.setItemLocation(hsmwItem.getLng()+","+hsmwItem.getLat());
                }
                HashMap params = new HashMap();
                params.put("orderId", hsmwOrder.getOrderId());
                List<HsmwConcreteInfo> hsmwConcreteInfoList = hsmwConcreteInfoMapper.selectConcretelist(params);
                hsmwOrder.setHsmwConcreteInfos(hsmwConcreteInfoList);

                List<HsmwOrderVehicleRequest> list = hsmwOrderVehicleRequestService.list(new LambdaQueryWrapper<HsmwOrderVehicleRequest>().eq(HsmwOrderVehicleRequest::getOrderId, hsmwOrder.getOrderId()));
                if(CollectionUtil.isNotEmpty(list)){
                    // 泵车单子
                    hsmwOrder.setType("1");
                }else {
                    hsmwOrder.setType("2");
                }
            }
        }
        return new DataResponse(hsmwOrders);
    }

    public Map findConcreteOrderListById(String id) {
        LoginUser hsmwUser = currentHsmwUserUtils.getCurrentUserInfo();
        Map map = new HashMap();
        OrderAndItemVO hsmwOrder = hsmwOrderMapper.findConcreteOrderListById(id);
        HashMap params = new HashMap();
        params.put("orderId", hsmwOrder.getOrderId());
        //查询有混凝土记录那么 直接查询如果 没有记录 就查询记录并 查询出来
        List<HsmwConcreteOperate> hsmwConcreteOperates = null;
        List<HsmwConcreteOperate> concreteOperates = hsmwConcreteOperateService.list(new LambdaQueryWrapper<HsmwConcreteOperate>()
                .eq(HsmwConcreteOperate::getOrderId, hsmwOrder.getOrderId()));
        if (CollectionUtil.isEmpty(concreteOperates)) {
            //查询出全部的混凝土的标号的类型
            List<HsmwConcreteInfo> hsmwConcreteInfoList = hsmwConcreteInfoMapper.selectConcretelist(params);
            hsmwConcreteInfoList.stream().forEach(hsmwConcreteInfo -> {
                HsmwConcreteOperate operate = new HsmwConcreteOperate();
                operate.setOrderId(hsmwOrder.getOrderId());
                operate.setConcreteNum(hsmwConcreteInfo.getConcreteNum());
                operate.setExpectVolume(hsmwConcreteInfo.getExpectVolume());
                operate.setSlump(hsmwConcreteInfo.getSlump());
                operate.setIncreaseandOrDecrease(hsmwConcreteInfo.getIncreaseandOrDecrease());
                operate.setOperUser(hsmwUser.getId());
                hsmwConcreteOperateMapper.insert(operate);
            });
            hsmwConcreteOperates = hsmwConcreteOperateMapper.selectList(new LambdaQueryWrapper<HsmwConcreteOperate>()
                    .eq(HsmwConcreteOperate::getOrderId, hsmwOrder.getOrderId()));
        } else {
            hsmwConcreteOperates = concreteOperates;
        }
        hsmwOrder.setHsmwConcreteOperates(hsmwConcreteOperates);
        List<HsmwConcreteInfo> hsmwConcreteInfoList = hsmwConcreteInfoMapper.selectConcretelist(params);
        hsmwOrder.setHsmwConcreteInfos(hsmwConcreteInfoList);
        List<HsmwConcreteOperateRecord> hsmwConcreteOperateRecords = hsmwConcreteOperateRecordMapper.selectList(new LambdaQueryWrapper<HsmwConcreteOperateRecord>().eq(HsmwConcreteOperateRecord::getOrderId, id).in(HsmwConcreteOperateRecord::getOperType,"1","4").orderByDesc(HsmwConcreteOperateRecord::getCreateTime));
        if(CollectionUtil.isNotEmpty(hsmwConcreteOperateRecords)){
            hsmwOrder.setHsmwConcreteOperateRecords(hsmwConcreteOperateRecords);
        }
        map.put("hsmwOrder",hsmwOrder);
        return map;
    }

    public void updateConcreteVolume(QueryParamsVO queryParamsVO) {
        LoginUser user = currentHsmwUserUtils.getCurrentUserInfo();
        List<QueryVO> queryVOS = queryParamsVO.getQueryVOS();
        String orderId= "";
        Double ensureVolume = 0.0;
        for (QueryVO queryVO : queryVOS) {
            HsmwConcreteOperate hsmwConcreteOperate = hsmwConcreteOperateService.getById(queryVO.getConcreteId());
            hsmwConcreteOperate.setConcreteVolume(queryVO.getConcreteVolume());
            hsmwConcreteOperateService.updateById(hsmwConcreteOperate);
            orderId= hsmwConcreteOperate.getOrderId();
            ensureVolume+=(StringUtils.isNotBlank(queryVO.getConcreteVolume()) ? Double.valueOf(queryVO.getConcreteVolume()):0.00);
        }
        //更新混凝土订单的确认方量
        HsmwOrderVehicleRequest request  = hsmwOrderVehicleRequestService.getById(queryParamsVO.getRequestId());
        request.setEnsureVolume(ensureVolume.toString());
        request.setEnsureVolumeFlag(CommonConstants.YES);
        hsmwOrderVehicleRequestService.updateById(request);
        HsmwConcreteOperateRecord record = new HsmwConcreteOperateRecord();
        record.setOrderId(orderId);
        record.setOperUser(user.getId());
        record.setOperType(OperTypeEnum.COMMIT.getValue());
        record.setRemark("搅拌站提交方量");
        hsmwConcreteOperateRecordService.save(record);
    }

    public Map findOrderListInfoByOrderId(String id) {

        Map map = new HashMap();
        //通过订单id查询需求车辆信息
        List<RequestVo> requestVos = hsmwOrderVehicleRequestService.findRequstListByOrderId(id);
        for (RequestVo requestVo : requestVos) {

            List<PositionAndDriverVo> positions = new ArrayList<>();
            PositionAndDriverVo positionServiceById = hsmwConstructionPositionService.findPositionAndDriverList(requestVo.getPositionId());
            PositionAndDriverVo position = new PositionAndDriverVo();
            position.setPosition(positionServiceById.getPosition());

            String requestId = requestVo.getReId();
            HsmwOrderVehicleRelation relation = hsmwOrderVehicleRelationService.getOne(new LambdaQueryWrapper<HsmwOrderVehicleRelation>().eq(HsmwOrderVehicleRelation::getOrderVehicleRequestId, requestId));
            if (relation == null) {
                continue;
            } else {
                position.setVehicleNum(relation.getVehicleNum());
                position.setOrderStatus(relation.getOrderStatus());
                requestVo.setOutsideLeasingFlag(relation.getOutsideLeasingFlag());

                String vehicleId = relation.getVehicleId();
                if (StringUtils.isNotBlank(vehicleId)) {
                    List<DriverDetailVO> driverDetailVOS = hsmwUserDriverService.findDriverListById(vehicleId);
                    position.setDriverDetailInfoVOS(driverDetailVOS);
                }
                positions.add(position);
            }
            requestVo.setPositionAndDriverVos(positions);
        }
        map.put("info",requestVos);
        return map;
    }

    public String refuseConcreteOrderById(String requestId) {
        HsmwOrderVehicleRequest request = hsmwOrderVehicleRequestService.getById(requestId);
        request.setConcreteOrderStatus(ConcreteOrderStatusEnum.CANCELED.getValue());
        //搅拌站取消的话 将 取消类型设置为 1
        request.setOperType(CancleTypeEnum.CONCRETE_CANCLE.getValue());
        request.setOperTime(LocalDateTime.now());
        request.setEndTime(LocalDateTime.now());
        boolean atc = hsmwOrderVehicleRequestService.updateById(request);
        HsmwHtnUser user = hsmwHtnUserService.getById(request.getCreateUser());
        if(atc){
            String msg = "您的混凝土订单被"+request.getConcretePlantName()+"拒绝，订单已被取消!";
                    //新增系统消息
                    HsmwDriverNews hsmwDriverNews = new HsmwDriverNews();
                    hsmwDriverNews.setUserId(user.getId());
                    hsmwDriverNews.setMessage(msg);
                    hsmwDriverNews.setAlreadyRead("0");
                    hsmwDriverNewsService.save(hsmwDriverNews);
                    TencentPushUtils.pushForeManMsg(msg,user.getUsername(),"");
          /*   //给工长推送信息 搅拌站拒绝订单 的信息
            HsmwConcretePlantInfo hsmwConcretePlantInfo = hsmwConcretePlantInfoMapper.selectById(request.getConcretePlantId());
            //给工长推送信息 搅拌站拒绝接单的信息
            TencentPushUtils.pushForeManMsg(msg,user.getUsername(),"");
            //发送混凝土订单的云打印
            YLYNewOrderDTO newOrderDTO = new YLYNewOrderDTO();
            newOrderDTO.setMechineId(hsmwConcretePlantInfo.getMechineId());
            newOrderDTO.setItemName(order.getItemName());
            newOrderDTO.setOrderId(order.getId());
            newOrderDTO.setConstructionUnitName(order.getConstructionUnitName());
            newOrderDTO.setItemPosition(order.getItemPosition());
            DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
            newOrderDTO.setReachTime(dtf.format(request.getReachTime()));
            newOrderDTO.setForemanName(order.getCreateName());
            newOrderDTO.setForemanTel(order.getCreateUserTel());
            newOrderDTO.setOperType(OperTypeEnum.CANCEL.getValue());
            YLWUtils.sendCancelOrder(newOrderDTO);*/
            return "suc";
        }
        return "err";
    }
    public String cancleConcreteOrderById(String requestId) {
        HsmwOrderVehicleRequest request = hsmwOrderVehicleRequestService.getById(requestId);
        request.setConcreteOrderStatus(ConcreteOrderStatusEnum.CANCELED.getValue());
        //搅拌站取消的话 将 取消类型设置为 1
        request.setOperType(CancleTypeEnum.CONCRETE_CANCLE.getValue());
        request.setOperTime(LocalDateTime.now());
        request.setEndTime(LocalDateTime.now());
        boolean atc = hsmwOrderVehicleRequestService.updateById(request);
        HsmwHtnUser user = hsmwHtnUserService.getById(request.getCreateUser());
        if(atc){
            HsmwOrder order = hsmwOrderMapper.selectById(request.getOrderId());
            String msg = "您的混凝土订单被"+request.getConcretePlantName()+"已被取消!";
            //给工长推送信息 搅拌站拒绝订单 的信息
            HsmwHtnUser  hsmwUser = currentHsmwUserUtils.getCurrentHtnUserInfo();
            //给工长推送信息 搅拌站拒绝接单的信息

            if(HtnUserTypeEnum.FOREMAN.getValue().equals(hsmwUser.getType()) || HtnUserTypeEnum.COMPANY.getValue().equals(hsmwUser.getType())  ||  ( HtnUserTypeEnum.CONCRETE.getValue().equals(hsmwUser.getType()) && !hsmwUser.getOwnCompanyId().equals(request.getConcretePlantId()) )){
                List<HsmwHtnUser> concreteUsers = hsmwHtnUserService.list(new LambdaQueryWrapper<HsmwHtnUser>()
                        .eq(HsmwHtnUser::getType,HtnUserTypeEnum.CONCRETE.getValue())
                        .eq(HsmwHtnUser::getOwnCompanyId,order.getConcretePlantId())
                        .eq(HsmwHtnUser::getRoleType,HtnUserRoleEnum.LEADING.getValue()));
                if(CollectionUtil.isNotEmpty(concreteUsers)){
                    HsmwHtnUser htnUser = concreteUsers.get(0);
                    TencentPushUtils.pushForeManMsg(msg,htnUser.getUsername(),"");
                    //新增系统消息
                    HsmwDriverNews hsmwDriverNews = new HsmwDriverNews();
                    hsmwDriverNews.setUserId(htnUser.getId());
                    hsmwDriverNews.setMessage(msg);
                    hsmwDriverNews.setAlreadyRead("0");
                    hsmwDriverNewsService.save(hsmwDriverNews);

                }
            }

/*
            if(HtnUserTypeEnum.FOREMAN.getValue().equals(hsmwUser.getType()) || HtnUserTypeEnum.COMPANY.getValue().equals(hsmwUser.getType())  ||  ( HtnUserTypeEnum.CONCRETE.getValue().equals(hsmwUser.getType()) && !hsmwUser.getOwnCompanyId().equals(request.getConcretePlantId()) )){
                HsmwConcretePlantInfo plantInfo = hsmwConcretePlantInfoMapper.selectById(request.getConcretePlantId());

                //发送混凝土订单的云打印
                YLYNewOrderDTO newOrderDTO = new YLYNewOrderDTO();
                newOrderDTO.setItemName(order.getItemName());
                newOrderDTO.setMechineId(plantInfo.getMechineId());
                newOrderDTO.setOrderId(order.getId());
                newOrderDTO.setConstructionUnitName(order.getConstructionUnitName());
                newOrderDTO.setItemPosition(order.getItemPosition());
                DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
                newOrderDTO.setReachTime(dtf.format(request.getReachTime()));
                newOrderDTO.setForemanName(order.getCreateName());
                newOrderDTO.setForemanTel(order.getCreateUserTel());
                newOrderDTO.setOperType(OperTypeEnum.CANCEL.getValue());
                YLWUtils.sendCancelOrder(newOrderDTO);
            }
*/

            return "suc";
        }
        return "err";
    }


    public IPage<ConcretePlantInfoVO> getConcretePlantList(BasePage page) {
        HashMap param =new HashMap();
        if(StringUtils.isNotBlank(page.getQueryParam())){
            param.put("queryParam",page.getQueryParam());
        }
        if(StringUtils.isNotBlank(page.getQueryParam())){
            param.put("orderStatus",page.getOrderStatus());
        }
        HashMap result = new HashMap();
        List<ConcretePlantInfoVO> allOrderList = hsmwConcretePlantInfoMapper.getConcretePlantList(param);
        param.put("pageStart",(page.getPageNo()-1) * page.getPageSize());
        param.put("pageSize",page.getPageSize());
        List<ConcretePlantInfoVO> orderList = hsmwConcretePlantInfoMapper.getConcretePlantList(param);
        IPage<ConcretePlantInfoVO> 	 orderPage =new Page<>();
        orderPage.setTotal(allOrderList.size());
        orderPage.setCurrent(page.getPageNo());
        orderPage.setRecords(orderList);
        orderPage.setSize(page.getPageSize());
        long total = allOrderList.size();
        long pages = 0;
        pages = total/page.getPageSize();
        if(total% page.getPageSize() !=0){
            pages = pages+1;
        }
        orderPage.setPages(pages);
        result.put("data",orderPage);
        return orderPage;
    }


    public ConcretePlantInfoVO getConcretePlantDetail(String plantId) {
        HashMap param = new HashMap();
        param.put("plantId",plantId);
        return hsmwConcretePlantInfoMapper.getConcretePlantDetail(param);
    }


    public HashMap getConcreteStatistics(ConcreteCountTypeVO concreteCountTypeVO) {
        HashMap result = new HashMap();
        HashMap param = new HashMap();
        param.put("itemId",concreteCountTypeVO.getItemId());
        param.put("year",concreteCountTypeVO.getYear());
        param.put("plantId",concreteCountTypeVO.getPlantId());
        param.put("month",concreteCountTypeVO.getYear()+"-"+concreteCountTypeVO.getMonth());

        List<ConcreteItemCountVO> dayList = hsmwConcreteInfoMapper.selectConcreteCountByMonth(param);
        result.put("dayList",dayList);
        List<ConcreteItemCountVO> itemCounts = hsmwConcreteInfoMapper.selectConcreteItemCount(param);
        result.put("itemCounts",itemCounts);
        LocalDate localDate = LocalDate.parse(concreteCountTypeVO.getYear()+"-"+concreteCountTypeVO.getMonth()+"-01", DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        //这个月的第一天
        Date monthStart = Date.from(localDate.with(TemporalAdjusters.firstDayOfMonth()).atStartOfDay(ZoneId.systemDefault()).toInstant());
        //这个月的最后一天 下个月的第一天
        Date monthEnd = Date.from(localDate.plusMonths(1).with(TemporalAdjusters.firstDayOfMonth()).atStartOfDay(ZoneId.systemDefault()).toInstant());
        DateTime endTime = DateUtil.date(monthEnd);
        DateTime startTime = DateUtil.date(monthStart);
        List<String> dayBetween = com.htn.common.core.utils.DateUtil.getDayBetween(DateUtil.format(startTime.toJdkDate(), "yyyy-MM-dd"), DateUtil.format(endTime.toJdkDate(), "yyyy-MM-dd"));
        dayBetween.remove(dayBetween.size()-1);
        result.put("dayBetween",dayBetween);
        return result;

    }

    public IPage<ConcreteOrderDTO>   selectOrderListByParam(BasePage page ){
        HashMap param =new HashMap();
        if(StringUtils.isNotBlank(page.getQueryParam())){
            param.put("queryParam",page.getQueryParam());
        }
        if(StringUtils.isNotBlank(page.getUserId())){
            param.put("userId",page.getUserId());
        }
        if(StringUtils.isNotBlank(page.getPlantId())){
            param.put("plantId",page.getPlantId());
        }
        if(StringUtils.isNotBlank(page.getItemId())){
            param.put("itemId",page.getItemId());
        }

        HashMap result = new HashMap();
        List<ConcreteOrderDTO> allOrderList =hsmwConcretePlantInfoMapper.selectOrderListByParam(param);
        param.put("pageStart",(page.getPageNo()-1) * page.getPageSize());
        param.put("pageSize",page.getPageSize());
        List<ConcreteOrderDTO> orderList =hsmwConcretePlantInfoMapper.selectOrderListByParam(param);
        IPage<ConcreteOrderDTO> 	 orderPage =new Page<>();
        orderPage.setTotal(allOrderList.size());
        orderPage.setCurrent(page.getPageNo());
        orderPage.setRecords(orderList);
        orderPage.setSize(page.getPageSize());
        long total = allOrderList.size();
        long pages = 0;
        pages = total/page.getPageSize();
        if(total% page.getPageSize() !=0){
            pages = pages+1;
        }
        orderPage.setPages(pages);
        result.put("data",orderPage);
        return orderPage;
    }

    public List<PositionRequestVO> findVehicleRequestById(String id) {


        return hsmwConcretePlantInfoMapper.findVehicleRequestById(id);
    }

    public DataResponse mixingReassignmentOrder(String id) {

        HsmwOrder hsmwOrder = hsmwOrderMapper.selectById(id);
        HsmwOrderVO hsmwOrderVO = new HsmwOrderVO();
        hsmwOrderVO.setItemId(hsmwOrder.getItemId());
        hsmwOrderVO.setId(id);
        hsmwOrderVO.setLng(hsmwOrder.getLng());
        hsmwOrderVO.setLat(hsmwOrder.getLat());
        List<HsmwOrderVehicleRequest> orderVehicleRequests = hsmwOrderVehicleRequestService.list(new LambdaQueryWrapper<HsmwOrderVehicleRequest>().eq(HsmwOrderVehicleRequest::getOrderId, id));
        hsmwOrderVO.setVehicleRequestList(orderVehicleRequests);
        ReturnVO returnVO = hsmwOrderService.compulsoryDispatchOrder(hsmwOrderVO);
        List<HsmwOrderVehicleRequest> hsmwOrderVehicleRequests = returnVO.getRequestList();
        for (HsmwOrderVehicleRequest hsmwOrderVehicleRequest : hsmwOrderVehicleRequests) {
            if(hsmwOrderVehicleRequest.getRequestStatus().equals("2")){
                for (HsmwOrderVehicleRequest orderVehicleRequest : orderVehicleRequests) {
                    orderVehicleRequest.setIfSelfChoose("1");
                }
                hsmwOrder.setIfSelfChoose("1");
            }
        }
        boolean b = hsmwOrderService.updateById(hsmwOrder);
        boolean b1 = hsmwOrderVehicleRequestService.updateBatchById(orderVehicleRequests);
        if(b && b1){
            return new DataResponse(CommonConstants.ResponseStatus.SUCCESS);
        }
        return new DataResponse(CommonConstants.ResponseStatus.FAIL);
    }


    public HashMap getItemStatistics(ConcreteCountTypeVO concreteCountTypeVO) {
        HashMap result = new HashMap();
        HashMap param = new HashMap();
        param.put("itemId",concreteCountTypeVO.getItemId());
        param.put("year",concreteCountTypeVO.getYear());
        param.put("plantId",concreteCountTypeVO.getPlantId());
        param.put("userId",concreteCountTypeVO.getUserId());

        param.put("month",concreteCountTypeVO.getYear()+"-"+concreteCountTypeVO.getMonth());
        List<ConcreteItemCountVO> dayList = hsmwConcreteInfoMapper.selectItemCount(param);

        LocalDate localDate = LocalDate.parse(concreteCountTypeVO.getYear()+"-"+concreteCountTypeVO.getMonth()+"-01", DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        //这个月的第一天
        Date monthStart = Date.from(localDate.with(TemporalAdjusters.firstDayOfMonth()).atStartOfDay(ZoneId.systemDefault()).toInstant());
        //这个月的最后一天 下个月的第一天
        Date monthEnd = Date.from(localDate.plusMonths(1).with(TemporalAdjusters.firstDayOfMonth()).atStartOfDay(ZoneId.systemDefault()).toInstant());
        DateTime endTime = DateUtil.date(monthEnd);
        DateTime startTime = DateUtil.date(monthStart);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(endTime);
        calendar.add(Calendar.DATE,-1);
        Date date =calendar.getTime();
        List<String> dayBetween = com.htn.common.core.utils.DateUtil.getDayBetween(DateUtil.format(startTime.toJdkDate(), "yyyy-MM-dd"), DateUtil.format(date, "yyyy-MM-dd"));
        result.put("dayList",dayList);
        List<ConcreteItemCountVO> itemCounts = hsmwConcreteInfoMapper.selectItemCount(param);
        result.put("itemCounts",itemCounts);
        result.put("dayBetween",dayBetween);
        return result;

    }

    public String receiveConcreteOrderById(String requestId) {
        HsmwHtnUser hsmwUser = currentHsmwUserUtils.getCurrentHtnUserInfo();
        HsmwOrderVehicleRequest request = hsmwOrderVehicleRequestService.getById(requestId);
        request.setConcreteOrderStatus(ConcreteOrderStatusEnum.RECEIVED.getValue());
        request.setAcceptOrderTime(LocalDateTime.now());
        boolean atc = hsmwOrderVehicleRequestService.updateById(request);
        //保存操作记录 记录搅拌站确认接单
        HsmwConcreteOperateRecord record = new HsmwConcreteOperateRecord();
        record.setOperUser(hsmwUser.getId());
        record.setRequestId(requestId);
        record.setOperType(OperTypeEnum.RECEIVE.getValue());
        hsmwConcreteOperateRecordService.save(record);
        //查询订单信息
        HsmwOrder allOrderInfo = hsmwOrderService.getById(request.getOrderId());

        //如果 搅拌站ID 和 当前登录人的 所属的搅拌站ID 不一样 就 发送打印
            //发送混凝土订单的云打印
            YLYNewOrderDTO newOrderDTO = new YLYNewOrderDTO();
            HsmwConcretePlantInfo plantInfo = hsmwConcretePlantInfoMapper.selectById(allOrderInfo.getConcretePlantId());
            newOrderDTO.setMechineId(plantInfo.getMechineId());
            newOrderDTO.setItemName(allOrderInfo.getItemName());
            newOrderDTO.setOrderId(allOrderInfo.getId());
            newOrderDTO.setConstructionUnitName(allOrderInfo.getConstructionUnitName());
            newOrderDTO.setItemPosition(allOrderInfo.getItemPosition());
            DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
            newOrderDTO.setReachTime(dtf.format(request.getReachTime()));
            newOrderDTO.setForemanName(allOrderInfo.getLinkmanName());
            newOrderDTO.setForemanTel(allOrderInfo.getLinkmanTelephone());
        /*if(CommonConstants.YES.equals(hsmwItem.getIfSelfChoose())){
            List<String > reqList = new ArrayList<>();
            List<HsmwOrderVehicleRequest> requests = hsmwOrderVehicleRequestService.list(new LambdaQueryWrapper<HsmwOrderVehicleRequest>()
                    .eq(HsmwOrderVehicleRequest::getOrderId,allOrderInfo.getId()));
            if(CollectionUtil.isNotEmpty(requests)){
                HashMap res= chooseReqInfo(requests);
                Set<String> keySet =res.keySet();
                for (String key:keySet){
                    reqList.add(key +"  "+res.get(key)+"  辆" );
                }
            }
            newOrderDTO.setPumpReqList(reqList);
        }*/
            HashMap param = new HashMap();
            param.put("orderId",allOrderInfo.getId());
            List<HsmwConcreteInfo> concreteInfos  = hsmwConcreteInfoMapper.selectConcretelist(param);
            newOrderDTO.setHsmwConcreteInfos(concreteInfos);
            newOrderDTO.setForemanTel(allOrderInfo.getCreateUserTel());
            YLWUtils.ensureNewOrder(newOrderDTO);
        if(atc){
            return "suc";
        }
        return "err";
    }

    public HashMap chooseReqInfo(List<HsmwOrderVehicleRequest> requestList) {
        HashMap result = new HashMap();
        for (HsmwOrderVehicleRequest request : requestList) {
            String key = request.getVehicleType() + " " + request.getVehicleModel();
            if (result.containsKey(key)) {
                int count = Integer.parseInt(result.get(key).toString());
                result.put(key, count + 1);
            } else {
                result.put(key, 1);
            }
        }
        return result;
    }

    public List<HsmwConcretePlantInfo> getAviablePlantInfos(String itemId) {
       return  hsmwOrderMapper.getAviablePlantInfos(itemId);
    }

    public void addPlantInfos(PlantInfoAddVO plantInfoAddVO) {
        LoginUser currentUser =currentHsmwUserUtils.getCurrentUserInfo();
        List<HsmwItemConcreteRelation> relations = new ArrayList<>();
        String[] ids = plantInfoAddVO.getPlantIds();
        for(int i=0;i<ids.length;i++){
            HsmwItemConcreteRelation relation = new HsmwItemConcreteRelation();
            relation.setConcreteId(ids[i]);
            relation.setItemId(plantInfoAddVO.getItemId());
            relation.setRemark("中控添加的搅拌站");
            relation.setCreateUser(currentUser.getId());
            relations.add(relation);
        }
        hsmwItemConcreteRelationService.saveBatch(relations);
    }



    public static void main(String[] args) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM");
        LocalDate localDate = LocalDate.now();
        LocalDate beginDate = localDate.minusMonths(11);
        System.out.println(formatter.format(localDate));
        System.out.println(formatter.format(beginDate));

    }
}
